package com.process.Imp.servUtil;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.StrUtil;
import cn.xuyanwu.spring.file.storage.FileInfo;
import cn.xuyanwu.spring.file.storage.recorder.FileRecorder;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.process.dao.pojoDao.FileDetailDao;
import com.process.domain.publi.FileDetail;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;

/**
 * @Description:
 * @ClassName: FileDetailService
 * @Author: 殷凡卓
 * @Date: 2023/4/21 21:13
 */
@Service
public class FileDetailService extends ServiceImpl<FileDetailDao, FileDetail> implements FileRecorder, com.process.service.ExcelServ.FileDetailService {


    /**
     * 保存文件信息到数据库
     */
    @SneakyThrows
    @Override
    public boolean record(FileInfo info) {
        FileDetail detail = BeanUtil.copyProperties(info, FileDetail.class,"attr");

        //这是手动获 取附加属性字典 并转成 json 字符串，方便存储在数据库中
        if (info.getAttr() != null) {
            Dict infoAttr = info.getAttr();
//            detail.setAttr(new ObjectMapper().writeValueAsString(info.getAttr()));

            Long pricticalId = infoAttr.getLong("pricticalId");
            String submitter = infoAttr.getStr("submitter");
            String mutualEvalu = infoAttr.getStr("mutualEvalu");
            String processId = infoAttr.getStr("processId");

            detail.setPricticalId(pricticalId);
            detail.setSubmitter(submitter);
            detail.setMutualEvalu(mutualEvalu);
            detail.setProcessId(processId);

        }
        boolean b = save(detail);
        if (b) {
            info.setId(detail.getId());
        }
        return b;
    }

    /**
     * 根据 url 查询文件信息
     */
    @SneakyThrows
    @Override
    public FileInfo getByUrl(String url) {
        FileDetail detail = getOne(new QueryWrapper<FileDetail>().eq("url",url));
        FileInfo info = BeanUtil.copyProperties(detail,FileInfo.class,"attr");

        //这是手动获取数据库中的 json 字符串 并转成 附加属性字典，方便使用
        if (StrUtil.isNotBlank(detail.getAttr())) {
            info.setAttr(new ObjectMapper().readValue(detail.getAttr(), Dict.class));
        }
        return info;
    }

    /**
     * 根据 url 删除文件信息
     */
    @Override
    public boolean delete(String url) {
        return remove(new QueryWrapper<FileDetail>().eq("url",url));
    }
}